package qwq.zyu.Hologram;

import eu.decentsoftware.holograms.api.DHAPI;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import qwq.zyu.qwqPlugin;


import java.util.*;
import java.util.regex.Pattern;


public class qwqShowTop10ScoreboardCommand implements CommandExecutor {

    private final qwqPlugin plugin;

    public qwqShowTop10ScoreboardCommand(qwqPlugin plugin) {
        this.plugin = plugin;
    }

    private final Map<String, List<String>> cachedTop10 = new HashMap<>();

    private static final Pattern UUID_PATTERN = Pattern.compile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$");

    public boolean isUUID(String s){
        return UUID_PATTERN.matcher(s).matches();
    }


    public boolean isUUID_2(String s){
        Pattern pattern = Pattern.compile("^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$");
        return pattern.matcher(s).matches();
    }

    public void updateCache(String scoreboardName,
                            boolean isDescending,
                            boolean putZeroToEnd,
                            boolean isSN,
                            boolean hideZero,
                            boolean hideVol,
                            boolean tickToSecond) {
        Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
        Objective objective = scoreboard.getObjective(scoreboardName);
        if ( objective == null ) return;
        cachedTop10.put(scoreboardName, this.getTop10Players(objective,isDescending,putZeroToEnd,isSN, hideZero,hideVol,tickToSecond));
    }

    public void updateCache(String scoreboardName, List<String> newList){
        cachedTop10.put(scoreboardName, newList);
    }

    public List<String> getCachedTop10(String scoreboardName) {
        return cachedTop10.getOrDefault(scoreboardName, new ArrayList<>(Collections.singletonList("暂无数据")));
    }


    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage("此命令仅供玩家使用。");
            return false;
        }

        if ( !(args.length>=12 && args.length<=13) ) {
            sender.sendMessage("用法: /qwq_show_top10_scoreboard <计分板名称> <降序？t/f> <把0放到末尾> <是否标序号？t/f> <隐藏0？t/f> <隐藏Vol? t/f> <tick美化成秒数? t/f> <x,y,z,pitch,yaw> [自定义标题]");
            return false;
        }

        String scoreboardName = args[0];
        boolean isDescending = Boolean.parseBoolean(args[1]);
        boolean putZeroToEnd = Boolean.parseBoolean(args[2]);
        boolean isSN = Boolean.parseBoolean(args[3]);
        boolean hideZero = Boolean.parseBoolean(args[4]);
        boolean hideVol = Boolean.parseBoolean(args[5]);
        boolean tickToSecond = Boolean.parseBoolean(args[6]);
        Location location = parseLocation((Player) sender, args[7], args[8], args[9], args[10], args[11]);

        String customTitle = args.length==13 ? args[12] : null;

        if (location == null) {
            sender.sendMessage("位置格式错误，示例：123,65,-456,0,180");
            return false;
        }

        // --- 开始：新增的参数输出部分 ---
        sender.sendMessage(ChatColor.DARK_AQUA + "--- " + ChatColor.BOLD + "命令参数概览" + ChatColor.DARK_AQUA + " ---");
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "计分板名称: " + ChatColor.WHITE + scoreboardName);
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "是否降序: " + ChatColor.YELLOW + (isDescending ? "是" : "否"));
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "零值置末: " + ChatColor.YELLOW + (putZeroToEnd ? "是" : "否"));
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "显示序号: " + ChatColor.YELLOW + (isSN ? "是" : "否"));
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "隐藏零值: " + ChatColor.YELLOW + (hideZero ? "是" : "否"));
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "隐藏Vol: " + ChatColor.YELLOW + (hideVol ? "是" : "否"));
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "Tick转秒: " + ChatColor.YELLOW + (tickToSecond ? "是" : "否"));
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "全息图位置: " + ChatColor.LIGHT_PURPLE +
                "X:" + ChatColor.WHITE + location.getX() + ChatColor.LIGHT_PURPLE +
                " Y:" + ChatColor.WHITE + location.getY() + ChatColor.LIGHT_PURPLE +
                " Z:" + ChatColor.WHITE + location.getZ() + ChatColor.LIGHT_PURPLE +
                " Yaw:" + ChatColor.WHITE + location.getYaw() + ChatColor.LIGHT_PURPLE +
                " Pitch:" + ChatColor.WHITE + location.getPitch());
        sender.sendMessage(ChatColor.AQUA + "  ▪ " + ChatColor.GOLD + "自定义标题: " + ChatColor.WHITE + (customTitle != null ? ChatColor.translateAlternateColorCodes('&', customTitle) : ChatColor.GRAY + "无"));
        sender.sendMessage(ChatColor.DARK_AQUA + "------------------------");
        // --- 结束：新增的参数输出部分 ---

        Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
        Objective objective = scoreboard.getObjective(scoreboardName);

        if (objective == null) {
            sender.sendMessage("未找到计分板：" + scoreboardName);
            return false;
        }

        List<String> top10Lines = getTop10Players(objective, isDescending, putZeroToEnd, isSN, hideZero, hideVol, tickToSecond);
        if ( customTitle != null ){
            customTitle = ChatColor.translateAlternateColorCodes('&', customTitle);
            top10Lines.add(0, customTitle);
        }

        // 检查是否已有同名 Hologram，避免重复创建
        if (DHAPI.getHologram(scoreboardName) != null) {
//            DHAPI.removeHologram(DHAPI.getHologram(scoreboardName));
            DHAPI.removeHologram(scoreboardName);
        }

        DHAPI.createHologram(scoreboardName, location, true, top10Lines);
        sender.sendMessage("已成功在 " + location + " 创建排行榜全息图！");
        return true;
    }

    public List<String> getTop10Players(Objective objective,
                                        boolean isDescending,
                                        boolean putZeroToEnd,
                                        boolean isSN,
                                        boolean hideZero,
                                        boolean hideVol,
                                        boolean tickToSecond) {
//        isSN = true;
        Map<String, Integer> scores = new HashMap<>();
        for (String entry : objective.getScoreboard().getEntries()) {
            Score score = objective.getScore(entry);
//            Bukkit.getLogger().info("entry = " + entry);
            if (score.isScoreSet()) {
//                if ( score.getScore()==0 ) continue;
                scores.put(entry, score.getScore());
            }
        }


        // 根据分数排序
        List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(scores.entrySet());
        sortedEntries.sort((a, b) -> isDescending ? b.getValue() - a.getValue() : a.getValue() - b.getValue());

        if ( putZeroToEnd ){
            List<Map.Entry<String, Integer>> zeroEntries = new ArrayList<>();
            Iterator<Map.Entry<String, Integer>> iterator = sortedEntries.iterator();
            while(iterator.hasNext()){
                Map.Entry<String, Integer> entry = iterator.next();
                if ( entry.getValue() == 0 ){
                    zeroEntries.add(entry);
                    iterator.remove();
                }
            }
            sortedEntries.addAll(zeroEntries);
        }

//        // --- 开始：输出 sortedEntries 到控制台 ---
//        Bukkit.getLogger().info(ChatColor.DARK_GREEN + "--- 已排序的计分板条目 (包括零值处理后) ---");
//        if (sortedEntries.isEmpty()) {
//            Bukkit.getLogger().info(ChatColor.GRAY + "  没有可显示的条目。");
//        } else {
//            for (int i = 0; i < sortedEntries.size(); i++) {
//                Map.Entry<String, Integer> entry = sortedEntries.get(i);
//                // 为了控制台输出清晰，移除颜色代码
//                Bukkit.getLogger().info(ChatColor.GREEN + "  " + (i + 1) + ". " + entry.getKey() + ": " + entry.getValue());
//            }
//        }
//        Bukkit.getLogger().info(ChatColor.DARK_GREEN + "---------------------------------------------");
//        // --- 结束：输出 sortedEntries 到控制台 ---


        List<String> top10Lines = new ArrayList<>();
        int count = 0;
        for (Map.Entry<String, Integer> entry : sortedEntries) {
//            Bukkit.getLogger().info("entry.getValue() = " + entry.getValue());
            if ( hideZero ){
                if ( entry.getValue()==0 ) continue;
            }
            if ( hideVol ){
                if ( entry.getKey().startsWith("Vol_") ) continue;
            }
//            String ValueNum_str = entry.getValue().toString();
            String ValueNum_str;
            if ( tickToSecond ){
                ValueNum_str = String.format("%.2f", (float)entry.getValue()/20.0);
            } else {
                //为什么函数名能这么jb长
                ValueNum_str = qwq.zyu.Utils.SecondTimeValueToCnString.convertSecondsToMinutesAndSeconds(entry.getValue());
            }
            String line = ChatColor.GOLD + "[" + entry.getKey() + "]: " + ChatColor.YELLOW + ValueNum_str;
            if ( isSN ){
                line = ChatColor.WHITE + "【" + qwq.zyu.Utils.NumberToChineseUtil.intToChinese(count+1) + "】" + line;
            }
//            top10Lines.add(entry.getKey() + ": " + entry.getValue());
            top10Lines.add(line);
            count++;
            if (count >= 10) break;
        }

//        return top10Lines.isEmpty() ? Collections.singletonList("暂无数据") : top10Lines;

        // 在返回前，将前十名计分板信息输出到控制台
//        Bukkit.getLogger().info(ChatColor.AQUA + "--- " + ChatColor.BOLD + "计分板 [" + objective.getDisplayName() + ChatColor.BOLD + "] Top 10 数据 ---");
//        if (top10Lines.isEmpty()) {
//            Bukkit.getLogger().info(ChatColor.YELLOW + "  暂无数据或所有数据被过滤。");
//        } else {
//            for (int i = 0; i < top10Lines.size(); i++) {
//                // 使用 ChatColor.stripColor 移除颜色代码，确保控制台输出清晰
//                Bukkit.getLogger().info(ChatColor.GRAY + "  " + (i + 1) + ". " + ChatColor.stripColor(top10Lines.get(i)));
//            }
//        }
//        Bukkit.getLogger().info(ChatColor.AQUA + "--------------------------------------------------");

        return top10Lines.isEmpty() ? new ArrayList<>(Collections.singletonList("暂无数据")) : top10Lines;

    }


    private Location parseLocation(Player player, String xStr, String yStr, String zStr, String pitchStr, String yawStr) {
        try {
            double x = Double.parseDouble(xStr);
            double y = Double.parseDouble(yStr);
            double z = Double.parseDouble(zStr);
            float pitch = Float.parseFloat(pitchStr);
            float yaw = Float.parseFloat(yawStr);
            return new Location(player.getWorld(), x, y, z, yaw, pitch);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}
